package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.service.LiveTagService;
import com.atguigu.tingshu.live.util.LiveAutoAddressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.List;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

    @Autowired
    private LiveRoomMapper liveRoomMapper;

    @Autowired
    private LiveTagService liveTagService;

    @Override
    public List<LiveRoom> findLiveList() {
        //  只需要查看直播的过期时间大于当前系统时间即可！
        return liveRoomMapper.selectList(new LambdaQueryWrapper<LiveRoom>().gt(LiveRoom::getExpireTime,new Date()));
    }

    @Override
    public LiveRoom saveLiveRoom(Long userId, LiveRoomVo liveRoomVo) {
        //	这个人，只能有一个直播间.
        LiveRoom liveRoom = this.getCurrentLive(userId);
        if (null != liveRoom){
            throw new GuiguException(ResultCodeEnum.EXIST_NO_EXPIRE_LIVE);
        }
        //	创建对象
        liveRoom = new LiveRoom();
        //	赋值 - 先做属性拷贝
        BeanUtils.copyProperties(liveRoomVo, liveRoom);
        liveRoom.setUserId(userId);
        //	创建完成直播间，就开播！
        liveRoom.setStatus("1");
        liveRoom.setAppName("live");
        liveRoom.setStreamName("guigu" + userId);
        //	设置直播间的过期时间：
        //	获取时间
        Date date = liveRoom.getExpireTime();
        long time = date.getTime() / 1000;
        //	工具类
        TencentLiveAddressVo tencentLiveAddressVo = LiveAutoAddressUtil.getAddressUrl(liveRoom.getStreamName(), time);
        liveRoom.setPushUrl(tencentLiveAddressVo.getPushWebRtcUrl());
        liveRoom.setPlayUrl(tencentLiveAddressVo.getPullWebRtcUrl());
        //	保存数据
        liveRoomMapper.insert(liveRoom);
        //	返回数据
        return liveRoom;
    }

    @Override
    public LiveRoom getCurrentLive(Long userId) {
        //	status = 1 expire_time > new date() userId = ?;
        LiveRoom liveRoom = liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>().eq(LiveRoom::getUserId, userId).gt(LiveRoom::getExpireTime, new Date()));
        //	返回数据
        return liveRoom;
    }
}
